package bit_poi.utils;

import bit_poi.domain.PrintUser;
import bit_poi.domain.User;
import cn.hutool.core.lang.Console;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuisama
 * @date 2023/01/04 14:27
 * 基于Hutool 的excel工具封装
 **/
public class POIUtils {
    /**
     * 从excel中读取数据为Map列表。默认第一行为标题行
     * @return
     */
    public static List<User> readFromExcel(String fileName) {
        // 默认从桌面获取学生信息表
        ExcelReader reader = ExcelUtil.getReader(fileName);
        List<User> users = reader.readAll(User.class);
        reader.close();
        return users;
    }

    /**
     * 根据数据库查回的数据输出表格
     *
     * @param absentStudents
     * @param queryTime
     * @return
     */
    public static boolean writeAbsentStudents2Excel(List<User> absentStudents, String queryTime) {
        if (absentStudents.size() == 0) {
            Console.log("当前条件下没有缺勤学生");
            return true;
        }
        // 1.生成输出表格name。规则为班级名称 + 查询时间 + result.xlsx
        User user = absentStudents.get(0);
        String className = user.getClassName();
        queryTime = queryTime.replaceAll("\\:","_");
        // 巨坑！文件名不能带英文冒号，有的话需要转义!
        String resultFileName = CommonUtils.DESKTOP + File.separator + className + queryTime  +
                CommonUtils.PROPS.getStr("fileOutputName");
        Console.log(resultFileName);
        // 2.转换为输出格式
        List<PrintUser> printUsers = convertUser2Print(absentStudents);
        // 3.输出到表格中
        try {
            // 在桌面生成输出表格
            ExcelWriter ew = ExcelUtil.getWriter(resultFileName);
            // 跳过首行
            ew.passCurrentRow();
            // 合并标题 - 标题列数
            ew.merge(3,className + "缺勤情况统计表");
            ew.addHeaderAlias("studentName","学生姓名");
            ew.addHeaderAlias("className","班级名称");
            ew.addHeaderAlias("phoneNum","手机号");
            // 写入列表内容到表格中
            ew.write(printUsers,true);
            // 关闭输出流
            ew.close();
            return true;
        }catch (Exception e) {
            Console.error("写回表格出错");
            e.printStackTrace();
            return false;
        }
    }

    private static List<PrintUser> convertUser2Print(List<User> absentStudents) {
        List<PrintUser> result = new ArrayList<>();
        for (User user : absentStudents) {
            PrintUser printUser = new PrintUser();
            printUser.setClassName(user.getClassName());
            printUser.setPhoneNum(user.getPhoneNum());
            printUser.setStudentName(user.getName());
            result.add(printUser);
        }
        // help gc
        absentStudents.clear();
        return result;
    }
}
